//
//  ARBaseModalAlertController.swift
//  AquaRaft
//
//  Created by 何启亮 on 2024/3/27.
//

import UIKit

/// 弹窗样式alert出来的控制器
class ARBaseModalAlertController: ARBaseViewController, UIGestureRecognizerDelegate {
    
    // MARK: - Init
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        self.bgAlpha = 0.5
        
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        
        self.modalTransitionStyle = .crossDissolve
        self.modalPresentationStyle = .overCurrentContext
    }
    
    override init() {
        self.bgAlpha = 0.5
        
        super.init()
        
        self.modalTransitionStyle = .crossDissolve
        self.modalPresentationStyle = .overCurrentContext
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - Property
    
    var autoDismiss: Bool = true
    
    var bgAlpha: Double {
        didSet {
            self.view.backgroundColor = .black.withAlphaComponent(bgAlpha)
        }
    }
    
    var baseContainerView: UIView {
        get {
            return _containerView
        }
    }
    
    // MARK: - LifeCycle
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.configVc()
    }
    
    private func configVc() {
        // 再设一遍bgalpha
        let alpha = self.bgAlpha
        self.bgAlpha = alpha
        
        self.view.addSubview(_containerView)
        _containerView.snp.makeConstraints { make in
            make.center.equalToSuperview()
        }
        
        // tap gesture
        let tap = UITapGestureRecognizer(target: self, action: #selector(clickBgView(_:)))
        tap.delegate = self
        self.view.addGestureRecognizer(tap)
    }
    
    // MARK: - Action
    
    @objc private func clickBgView(_ gesture: UIGestureRecognizer) {
        self.dismiss(animated: true)
    }
    
    // MARK: - UIGestureRecognizerDelegate
    
    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        let location = gestureRecognizer.location(in: view)
        
        if _containerView.frame.contains(location) {
            return false
        }
        return autoDismiss
    }
    
    // MARK: - Lazy
    
    private lazy var _containerView: UIView = {
       let view = UIView()
        view.backgroundColor = .clear
        return view
    }()
    
}
